using MediatR;
using MeetingManagement.Domain.Entities;
using MeetingManagement.Domain.Repositories;

namespace MeetingManagement.Application.Commands.Meetings.BookMettingRoom
{
    public class BookMeetingRoomCommandHandler : IRequestHandler<BookMeetingRoomCommand, Guid>
    {
        private readonly IRepository<MeetingRoom> _roomRepo;
        private readonly IRepository<User> _userRepo;
        private readonly IRepository<Meeting> _meetingRepo;
        public BookMeetingRoomCommandHandler(IRepository<MeetingRoom> roomRepo, IRepository<User> userRepo, IRepository<Meeting> meetingRepo)
        {
            _roomRepo = roomRepo;
            _userRepo = userRepo;
            _meetingRepo = meetingRepo;
        }

        public async Task<Guid> Handle(BookMeetingRoomCommand request, CancellationToken cancellationToken)
        {
            var room = _roomRepo.Get(request.MeetingRoomId);
            if (room == null || !room.IsActive)
                throw new Exception("会议室不存在或已禁用");


            var conflict = _meetingRepo.Query()
                .Where(m => m.MeetingRoomId == room.Id &&
                    request.StartTime < m.TimeSlot.End && request.EndTime > m.TimeSlot.Start)
                .Any();
            if (conflict)
                throw new Exception("该会议室在该时间段已被预订");

            var organizer = _userRepo.Get(request.OrganizerId);
            if (organizer == null)
                throw new Exception("发起人不存在");

            var meeting = Meeting.Schedule(
                request.Title,
                request.Description,
                request.StartTime,
                request.EndTime,
                room.Location,
                organizer.Id,
                room.Id
            );
            foreach (var pid in request.ParticipantIds.Distinct())
            {
                var user = _userRepo.Get(pid);
                if (user != null)
                    meeting.AddParticipant(user.Id);
            }
            await _meetingRepo.CreateAsync(meeting);
            return meeting.Id;
        }
    }
}
